/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.clinicplus.manager;

import br.com.foxline.clinicplus.entity.*;
import br.com.foxline.clinicplus.enums.*;
import br.com.foxline.clinicplus.service.*;
import br.com.foxline.clinicplus.service.odonto.OdontogramaService;
import br.com.foxline.clinicplus.util.Caracter;
import br.com.foxline.clinicplus.util.Msg;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import org.apache.commons.lang3.time.DateUtils;
import org.primefaces.component.selectonemenu.SelectOneMenu;
import org.primefaces.context.RequestContext;
import org.primefaces.event.CaptureEvent;
import org.primefaces.event.ScheduleEntryMoveEvent;
import org.primefaces.event.ScheduleEntryResizeEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.*;

/**
 *
 * @author roniere
 */
@ManagedBean
@ViewScoped
public class ManagerAgenda implements Serializable {

    @EJB
    private DiaryService diaryService;
    @EJB
    private CustomerService customerService;
    @EJB
    private WaitingLineService waitingLineService;
    @EJB
    private DoctorService doctorService;
    @EJB
    private UnattendedService unattendedService;
    @EJB
    private IncomeService incomeService;
    @EJB
    private ProcedureService procedureService;
    @EJB
    private AnnexService annexService;
    @EJB
    private SystemUserService systemUserService;
    @EJB
    private OperatorService operatorService;
    @EJB
    private CityService cityService;
    @EJB
    private AppraisalService appraisalService;
//  CRIAR PACIENTE
    private Customer customerCreate;
    private Customer customerEdit;
    private Customer aux;
    private Customer customer;
    private Customer customerSearch;
    private Customer customerSearchDiary;
    private Customer customerSelect;
    private Operator operatorCreate;
    private Address address;
    private City city;
    private String url;
    private Annex annex;
    private ScheduleModel eventModel;
    private ScheduleModel eventModelHoje;
    private ScheduleEvent event = new DefaultScheduleEvent();
    private Diary diary;
    private Procedure procedureSearch;
    private Procedure procedure;
    private Procedure procedureSelect;
    private Procedure procedureSelectDialog;
    private Operator operator;
    private Operator operatorEdit;
    private Operator operatorSelect;
    private Doctor doctor;
    private Doctor doctorCreate;
    private Doctor doctorRequest;
    private Doctor doctorRequestSelect;
    private Doctor doctorSelect;
    private Doctor doctorSelectDialog;
    private List<Customer> customers;
    private List<Operator> operators;
    private List<Diary> diarys;
    private List<Diary> diarysSearch;
    private List<WaitingLine> waitingLines;
    private WaitingLine selectedWaitingLine;
    private Boolean blocker;
    private Income income;
    private List<Doctor> doctors;
    private List<Diary> diarysSelected;
    private List<Diary> diarysDisp;
    private List<Customer> searchCustomers;
    private List<Procedure> procedures;
    private boolean close = true;
    private BigDecimal discount;
    private Boolean retorno;
    private List<Diary> diarysRetorno;
    private String strRetorno;
    private boolean gender;
    private boolean photoedit;
    private String msg;
    private String dataNovoAtendimento;

    public String getDataNovoAtendimento() {
        return dataNovoAtendimento;
    }

    public void setDataNovoAtendimento(String dataNovoAtendimento) {
        this.dataNovoAtendimento = dataNovoAtendimento;
    }


    
    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public void initCustomer() {
//        if(this.customer != null && this.customer.getOperator() != null){
//            
//        }
        this.customerSelect = new Customer();
        this.customerCreate = new Customer();
        this.customerEdit = new Customer();
        this.customerSearch = new Customer();
        this.searchCustomers = new ArrayList<Customer>();
        this.address = new Address();
        this.city = new City();
        this.operatorCreate = new Operator();
        this.operatorEdit = new Operator();
        this.annex = new Annex();

        try {
            city = cityService.autocomplete("Parnaíba").get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @PostConstruct
    public void init() {
        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();

        if (params.get("type") != null) {
            if (params.get("type").equals("d")) {
                this.doctorSelect = new Doctor();
                this.procedureSelect = null;
            } else if (params.get("type").equals("p")) {
                this.procedureSelect = new Procedure();
                this.doctorSelect = null;
            }
        }

        gender = false;

        initSchedule();

        this.diary = new Diary();
        this.customer = new Customer();
        this.customerSearch = new Customer();
        this.customerSearchDiary = new Customer();
        this.procedure = new Procedure();
        this.operator = new Operator();
        this.doctor = new Doctor();
        this.doctorRequest = new Doctor();
        this.diarys = new ArrayList<Diary>();
        this.diarysSearch = new ArrayList<Diary>();
        this.waitingLines = new ArrayList<WaitingLine>();
        this.selectedWaitingLine = new WaitingLine();
        this.blocker = false;
        this.income = new Income();
        this.diarysSelected = new ArrayList<Diary>();
        this.diarysDisp = new ArrayList<Diary>();


        if (params.get(
                "d") != null) {
            try {
                this.doctorSelect = doctorService.find(Long.parseLong(params.get("d")));
                this.blocker = true;
                selectDoctor();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        loadWaitingLine();

        initCustomer();
        initProcedure();
        initDoctor();
        operators = operatorService.findAll();

    }

    public void initDoctor() {
        this.doctorCreate = new Doctor();
    }

    public void initProcedure() {

        procedureSearch = new Procedure();
        procedures = new ArrayList<Procedure>();

    }

    private void initSchedule() {

        this.eventModel = new LazyScheduleModel() {

            @Override
            public void loadEvents(Date start, Date end) {
                clear();
                loadDiary(start, end);
            }
        };
        this.eventModelHoje = new LazyScheduleModel() {

            @Override
            public void loadEvents(Date start, Date end) {
                clear();
                loadDiaryHoje(start, end);
            }
        };

    }

    public void selectProcedure() {
        initSchedule();
        this.procedure = this.procedureSelect;
        loadWaitingLine();
    }

    public void selectDoctor() {
        initSchedule();
        this.doctor = this.doctorSelect;
        loadWaitingLine();
    }

    private void loadWaitingLine() {
        if ((doctorSelect != null && doctorSelect.getId() != null)
                || (procedureSelect != null && procedureSelect.getId() != null)) {
            this.waitingLines = waitingLineService.getWaitingLineForProcedure(procedureSelect, doctorSelect);
        }
    }

    private void loadDiary(Date dateInitial, Date dateFinal) {
        DefaultScheduleEvent eventObj;

        if (procedureSelect != null && procedureSelect.getId() != null) {
            this.diarys = diaryService.getDiaryForProcedure(procedureSelect, dateInitial, dateFinal);
        }
        if (doctorSelect != null && doctorSelect.getId() != null) {
            this.diarys = diaryService.getDiaryForDoctor(doctorSelect, dateInitial, dateFinal);
        }
        for (Diary d : this.diarys) {
            String title = d.getCustomer().getName() + " - " + (d.getRetorno() != null ? (d.getRetorno() ? "RETORNO - " : "") : "")
                    + (d.getProcedure() == null ? "" + d.getDoctor().getName() : d.getProcedure().getName());
            eventObj = new DefaultScheduleEvent(title, d.getStartTime(), d.getEndTime(), d);
            if (d.getDiarySituation() != null) {
                eventObj.setStyleClass(d.getDiarySituation().toString().toLowerCase().replace(" ", "_"));

                if (d.getStatus() == false) {
                    eventObj.setStyleClass(DiarySituation.CALL_ENDED.toString().toLowerCase().replace(" ", "_"));
                }

            }
            eventModel.addEvent(eventObj);
        }

        for (Unattended unattended : unattendedService.findUnattended(doctor)) {
            eventObj = new DefaultScheduleEvent(doctor.getName() + " - " + unattended.getDescription(),
                    unattended.getStartTime(), unattended.getEndTime(), unattended);
            eventModel.addEvent(eventObj);

        }

    }
    private void loadDiaryHoje(Date dateInitial, Date dateFinal) {
        DefaultScheduleEvent eventObj;

        if (procedureSelect != null && procedureSelect.getId() != null) {
            this.diarys = diaryService.getDiaryForProcedure(procedureSelect, dateInitial, dateFinal);
        }
        if (doctorSelect != null && doctorSelect.getId() != null) {
            this.diarys = diaryService.getDiaryForDoctor(doctorSelect, dateInitial, dateFinal);
        }
        for (Diary d : this.diarys) {
            String title = d.getCustomer().getName() + " - " + (d.getRetorno() != null ? (d.getRetorno() ? "RETORNO - " : "") : "")
                    + (d.getProcedure() == null ? "" + d.getDoctor().getName() : d.getProcedure().getName());
            eventObj = new DefaultScheduleEvent(title, d.getStartTime(), d.getEndTime(), d);
            if (d.getDiarySituation() != null) {
                eventObj.setStyleClass(d.getDiarySituation().toString().toLowerCase().replace(" ", "_"));

                if (d.getStatus() == false) {
                    eventObj.setStyleClass(DiarySituation.CALL_ENDED.toString().toLowerCase().replace(" ", "_"));
                }

            }
            eventModelHoje.addEvent(eventObj);
        }

        for (Unattended unattended : unattendedService.findUnattended(doctor)) {
            eventObj = new DefaultScheduleEvent(doctor.getName() + " - " + unattended.getDescription(),
                    unattended.getStartTime(), unattended.getEndTime(), unattended);
            eventModelHoje.addEvent(eventObj);

        }

    }

    public List<SelectItem> selectTypeDiary() {
        List<SelectItem> diarySituation = new ArrayList<SelectItem>();
        for (DiarySituation ms : DiarySituation.values()) {
            diarySituation.add(new SelectItem(ms, ms + ""));
        }
        if (diary != null && diary.getId() != null && !verifyAdmin()) {
            List<SelectItem> removeList = new ArrayList<SelectItem>();
            for (SelectItem selectItem : diarySituation) {
                if (selectItem.getValue() == DiarySituation.CANCEL) {
                    removeList.add(selectItem);
                }
            }
            diarySituation.removeAll(removeList);
        }
        return diarySituation;
    }

    public List<SelectItem> selectPaymentType() {
        List<SelectItem> paymentTypes = new ArrayList<SelectItem>();
        for (PaymentType ms : PaymentType.values()) {
            paymentTypes.add(new SelectItem(ms, ms.getName()));
        }
        return paymentTypes;
    }

    public Operator getOperator() {
        return operator;
    }

    public void setOperator(Operator operator) {
        this.operator = operator;
    }

    public Procedure getProcedure() {
        return procedure;
    }

    public void setProcedure(Procedure procedure) {
        this.procedure = procedure;
    }

    public ScheduleEvent getEvent() {
        return event;
    }

    public void setEvent(ScheduleEvent event) {
        this.event = event;
    }

    public void addEvent(ActionEvent actionEvent) {
        try {

            boolean required = false;
            if (operator == null || operator.getId() == null) {
                Msg.messagemError("Convênio é obrigatório");
                required = true;
            }
            if (procedure == null || procedure.getId() == null) {



                Msg.messagemError("Procedimento é obrigatório");
                required = true;
            }
            if (doctor == null || doctor.getId() == null) {
                Msg.messagemError("Médico Responsável é obrigatório");
                required = true;
            }

            if (required) {
                diary.setDiarySituation(DiarySituation.SCHEDULED);
                return;
            }

            DefaultScheduleEvent eventObj;
            if (procedure != null && procedure.getId() != null) {
                diary.setProcedure(procedure);
            } else {
                diary.setProcedure(null);
            }

            if (customer != null && customer.getId() == null) {
                Msg.messagemError("Selecione um Paciente");
                return;
            }

            if (doctor != null && doctor.getId() != null) {
                diary.setDoctor(doctor);
            } else {
                diary.setDoctor(null);
            }

            if (doctorRequest != null && (doctorRequest.getId() != null)) {
                diary.setDoctorRequest(doctorRequest);
            } else {
                diary.setDoctorRequest(null);
            }

            if (customer != null && customer.getId() != null) {
                diary.setCustomer(customer);
            } else {
                diary.setCustomer(null);
            }

            System.err.println("DIARY: " + operator);
            if (operator == null || (operator != null && operator.getId() == null)) {
                diary.setOperator(null);
                this.customer.setOperator(null);
                customerService.update(customer);
            } else if (operator.getId() != null) {
                diary.setOperator(operator);
                this.customer.setOperator(operator);
                customerService.update(customer);
            }


            diary.setStatus(true);

            if (event.getId() == null) {
                String title = (customer != null ? customer.getName() : "") + " - "
                        + (procedure == null ? doctor.getName() : procedure.getName());

                diary.setStartTime(event.getStartDate());
                diary.setEndTime(event.getEndDate());
                diary.setCancel(false);

                if (diary.getId() == null) {
                    diary.setSystemUser(systemUserService.getCurrentUser());
                    diary.setCreateAt(new Date());
                    diaryService.save(diary);
                } else {
                    diary.setSystemUserUpdate(systemUserService.getCurrentUser());
                    diary.setUpdateAt(new Date());
                    diaryService.update(diary);
                }

                eventObj = new DefaultScheduleEvent(title, event.getStartDate(), event.getEndDate(), diary);
                eventObj.setStyleClass(diary.getDiarySituation() != null ? diary.getDiarySituation().toString().toLowerCase().replace(" ", "_") : "");
                eventModel.addEvent(eventObj);
                diarys.add(diary);

            } else {
                String title = (customer != null ? customer.getName() : "") + " - " + (procedure != null ? procedure.getName() : "");
                diary.setStartTime(event.getStartDate());
                diary.setEndTime(event.getEndDate());
                diary.setSystemUserUpdate(systemUserService.getCurrentUser());
                diary.setUpdateAt(new Date());
                diaryService.update(diary);

                if (diarys.contains(diary)) {
                    diarys.set(diarys.indexOf(diary), diary);
                }
                eventObj = new DefaultScheduleEvent(title, event.getStartDate(), event.getEndDate(), diary);
                eventObj.setId(event.getId());
                eventObj.setStyleClass(diary.getDiarySituation() != null ? diary.getDiarySituation().toString().toLowerCase().replace(" ", "_") : " ");

                eventModel.updateEvent(eventObj);
            }

            if (diary.getId() != null && incomeService.diaryByIncome(diary) != null) {
                Income i = incomeService.diaryByIncome(diary);
                if (i != null && i.getProcedure() == null && diary.getProcedure() != null) {
                    i.setProcedure(diary.getProcedure());
                    incomeDlgAoAtualizarAgenda();
                    RequestContext.getCurrentInstance().update(":diaryForm:fPanel");
                    RequestContext.getCurrentInstance().update(":diaryForm:famount");
                    RequestContext.getCurrentInstance().update(":diaryForm:famountpaid");
                    RequestContext.getCurrentInstance().update(":diaryForm:ftotalamount");
                    RequestContext.getCurrentInstance().update(":diaryForm:fPanel");
                    RequestContext.getCurrentInstance().execute("fDialog.show()");
                    close = false;
                }
                if (i != null && procedure != null && (i.getProcedure() != null
                        && procedure.getId() != i.getProcedure().getId())) {
                    i.setProcedure(diary.getProcedure());
                    incomeDlgAoAtualizarAgenda();
                    RequestContext.getCurrentInstance().update(":diaryForm:fPanel");
                    RequestContext.getCurrentInstance().update(":diaryForm:famount");
                    RequestContext.getCurrentInstance().update(":diaryForm:famountpaid");
                    RequestContext.getCurrentInstance().update(":diaryForm:ftotalamount");
                    RequestContext.getCurrentInstance().update(":diaryForm:fPanel");
                    RequestContext.getCurrentInstance().execute("fDialog.show()");
                    close = false;
                }
            }


            RequestContext context = RequestContext.getCurrentInstance();
            context.execute("myschedule.update()");
            if (close) {
                diary = new Diary();
                //procedure = new Procedure();
                customer = new Customer();
                eventObj = new DefaultScheduleEvent();
                event = new DefaultScheduleEvent();
                context.execute("eventDialog.hide();");
            }
            close = true;
        } catch (Exception e) {
            e.printStackTrace();
            Msg.messagemError("Ocorreu um Erro !");
        }
    }

    public void saveIncome() {



        if (this.diary != null && this.diary.getId() == null) {
            close = false;
            addEvent(null);
        }

        if (income.isPermissionEditAdmin() && !systemUserService.verifyAdmin()) {
            RequestContext.getCurrentInstance().update(":diaryForm:fPanel:msgincome");
            Msg.messagemWarn("Você não possui permissão para alterar informações de financeiras!");
            return;
        }

        if ((income.getAmount() == null || income.getAmount().compareTo(BigDecimal.ZERO) == 0
                || (income.getAmountPaid() == null
                || (income.getAmountPaid().compareTo(BigDecimal.ZERO) == 0
                && (income.getDiscount() != null && income.getDiscount().compareTo(income.getAmount()) == -1))))
                && diary != null && diary.getId() != null
                && diary.getOperator() != null
                && diary.getOperator().getId() != null
                && !(diary.getOperator().getName().equalsIgnoreCase("SUS")
                || diary.getOperator().getName().equalsIgnoreCase("cortesia"))) {

            Msg.messagemWarn("Valor pago não pode ser zero ou vazio");
            return;

        }

        if (procedure != null && procedure.getId() == null) {
            income.setProcedure(null);
        }
        if (doctor != null && doctor.getId() == null) {
            income.setDoctor(null);
        }

        if (income.getId() == null) {
            income.setDiary(diary);
            income.setSystemUser(systemUserService.getCurrentUser());
            if (income.getCreateAt() == null) {
                income.setCreateAt(new Date());
            }
            income.setTypeIncome(TypeIncome.C);
            incomeService.save(income);
            System.err.println("$$$ ENTRADA CAIXA nº" + income.getId() + " por: " + income.getSystemUser().getName() + " valor : " + income.getAmountPaid());
            diary.setIncome(income);
            diary.setSystemUserUpdate(systemUserService.getCurrentUser());
            diary.setUpdateAt(new Date());
            diaryService.update(diary);
            income = incomeService.find(income.getId());
        } else {
            incomeService.update(income);
            income = incomeService.find(income.getId());
        }

        RequestContext context = RequestContext.getCurrentInstance();
        context.update(":diaryForm:fPanel");
        context.execute("fDialog.hide();");

    }

    public void incomeDlg() {
        Income diaryByIncome = incomeService.diaryByIncome(diary);
        if (diaryByIncome == null) {
            income = new Income();
            if (doctor != null && doctor.getId() != null) {
                income.setDoctor(doctor);
            }
            income.setCreateAt(new Date());
            income.setProcedure(procedure);
            income.setSystemUser(systemUserService.getCurrentUser());

            income.setAmount(procedureService.getValueProcedureOperator(procedure, operator));
            income.setDiscount(BigDecimal.ZERO);
            income.setTotalAmount(income.getAmount());
            income.setAmountPaid(income.getAmount());

        } else {
            income = diaryByIncome;
        }

    }

    public void incomeDlgAoAtualizarAgenda() {
        Income diaryByIncome = incomeService.diaryByIncome(diary);
        if (diaryByIncome != null) {
            income = diaryByIncome;
            income.setProcedure(procedure);
            income.setAmount(procedureService.getValueProcedureOperator(procedure, operator));
            income.setDiscount(BigDecimal.ZERO);
            income.setTotalAmount(income.getAmount());
            income.setAmountPaid(income.getAmount());
        }

    }

    public void updateStatusEvent() {
        try {

            boolean required = false;
            if (operator == null || operator.getId() == null) {
                Msg.messagemError("Convênio é obrigatório");
                required = true;
            }
            if (procedure == null || procedure.getId() == null) {
                Msg.messagemError("Procedimento é obrigatório");
                required = true;
            }
            if (doctor == null || doctor.getId() == null) {
                Msg.messagemError("Médico Responsável é obrigatório");
                required = true;
            }

            if (required) {
                diary.setDiarySituation(DiarySituation.SCHEDULED);
                return;
            }

            if (this.diary != null && this.diary.getDiarySituation() == DiarySituation.CALL_WAITING) {
                Calendar gc = GregorianCalendar.getInstance();
                gc.add(GregorianCalendar.DAY_OF_MONTH, 1);
                gc.set(GregorianCalendar.MINUTE, 0);
                gc.set(GregorianCalendar.SECOND, 0);
                gc.set(GregorianCalendar.MILLISECOND, 0);

                if (this.event.getStartDate().after(gc.getTime())) {
                    Msg.messagemWarn("Data incorreta, a situação só pode ser alterada no dia do atendimento!");
                    RequestContext context = RequestContext.getCurrentInstance();
                    context.execute("dialogmsg.show();");
                    return;
                }


                if (incomeService.diaryByIncome(diary) != null) {
                    Income i = incomeService.diaryByIncome(diary);
                    i.setPermissionEditAdmin(true);
                    incomeService.update(i);
                }
            }

            if (customer != null && customer.getId() == null) {
                Msg.messagemError("Selecione um Paciente");
                return;
            }

            DefaultScheduleEvent eventObj;
            if (this.diary != null && this.diary.getId() == null) {
                close = false;
                addEvent(null);
            }

            if (this.diary.getDiarySituation() == DiarySituation.CALL_WAITING) {


//                incomeDlg();
//                RequestContext.getCurrentInstance().update(":diaryForm:fPanel");
//                RequestContext.getCurrentInstance().execute("fDialog.show()");

                WaitingLine waitingLine;
                if (this.diary != null && waitingLineService.getWaitingLineForDiary(this.diary.getId()) == null) {
                    waitingLine = new WaitingLine();
                    waitingLine.setDiary(this.diary);
                    waitingLine.setInitial(new Date());
                    waitingLine.setStatus(true);
                    waitingLineService.save(waitingLine);
                }

            }

            if (procedure != null && procedure.getId() != null) {
                this.diary.setProcedure(procedure);
            } else {
                this.diary.setProcedure(null);
            }

            if (doctor != null && doctor.getId() != null) {
                this.diary.setDoctor(doctor);
            } else {
                this.diary.setDoctor(null);
            }

            if (doctorRequest != null && doctorRequest.getId() != null) {
                this.diary.setDoctorRequest(doctorRequest);
            } else {
                this.diary.setDoctorRequest(null);
            }




            if (operator == null || (operator != null && operator.getId() == null)) {
                this.diary.setOperator(null);
                this.customer.setOperator(null);
                customerService.update(customer);
            } else if (operator.getId() != null) {
                this.diary.setOperator(operator);
                this.customer.setOperator(operator);
                customerService.update(customer);
            }

            if (event.getId() == null) {

                String title = (customer != null ? customer.getName() : "") + " - " + (procedure != null ? procedure.getName() : "");
                diary.setStartTime(event.getStartDate());
                diary.setEndTime(event.getEndDate());
                if (diary.getId() == null) {
                    this.diary.setCreateAt(new Date());
                    diary.setSystemUser(systemUserService.getCurrentUser());
                    diaryService.save(diary);
                } else {
                    diary.setSystemUserUpdate(systemUserService.getCurrentUser());
                    diary.setUpdateAt(new Date());
                    diaryService.update(diary);
                }
                eventObj = new DefaultScheduleEvent(title, event.getStartDate(), event.getEndDate(), diary);
                eventObj.setStyleClass(diary.getDiarySituation() != null ? diary.getDiarySituation().toString().toLowerCase().replace(" ", "_") : " ");
                eventModel.addEvent(eventObj);
            } else {
                String title = (customer != null ? customer.getName() : "") + " - " + (procedure != null ? procedure.getName() : "");
                diary.setStartTime(event.getStartDate());
                diary.setEndTime(event.getEndDate());
                diary.setSystemUserUpdate(systemUserService.getCurrentUser());
                diary.setUpdateAt(new Date());
                diaryService.update(diary);
                eventObj = new DefaultScheduleEvent(title, event.getStartDate(), event.getEndDate(), diary);
                eventObj.setId(event.getId());
                eventObj.setStyleClass(diary.getDiarySituation() != null ? diary.getDiarySituation().toString().toLowerCase().replace(" ", "_") : " ");
                eventModel.updateEvent(eventObj);
            }
            loadWaitingLine();

            RequestContext context = RequestContext.getCurrentInstance();
            context.execute("myschedule.update()");

        } catch (Exception e) {
            e.printStackTrace();
            Msg.messagemError("Ocorreu um Erro !");
        }

        System.err.println("" + procedure);
        if (this.diary.getDiarySituation() != null && this.diary.getDiarySituation() == DiarySituation.CALL_ENDED
                && procedure != null && procedure.getTypeProcedure() == TypeProcedure.EXAME && procedure.getAppraisal()) {

            Appraisal appraisal = new Appraisal();
            appraisal.setCustomer(diary.getCustomer());
            appraisal.setCreatAt(new Date());
            appraisal.setDiary(diary);
            appraisal.setSystemUser(systemUserService.getCurrentUser());
            appraisal.setSituationAppraisal(SituationAppraisal.WAITING);
            appraisalService.save(appraisal);

        }

        if (this.diary.getDiarySituation() == DiarySituation.CALL_WAITING) {
            if (!this.diary.getRetorno()) {
                incomeDlg();
                RequestContext.getCurrentInstance().update(":diaryForm:fPanel");
                RequestContext.getCurrentInstance().execute("fDialog.show()");
            }
        } else if (this.diary.getDiarySituation() == DiarySituation.CANCEL) {

            if (incomeService.diaryByIncome(diary) != null) {
                Income i = incomeService.diaryByIncome(diary);
                diary.setIncome(null);
                diary.setSystemUserUpdate(systemUserService.getCurrentUser());
                diary.setUpdateAt(new Date());
                diaryService.update(diary);
                incomeService.delete(i);
            }
        }
    }

    public void clean() {
        diary = new Diary();
        event = new DefaultScheduleEvent();
        procedure = new Procedure();
        customer = new Customer();
        doctorRequest = new Doctor();
        operator = new Operator();
        gender = true;

    }

    public void onEventSelect(SelectEvent selectEvent) {
        event = (ScheduleEvent) selectEvent.getObject();

        if (event == null || event.getData() instanceof Unattended) {
            return;
        }
        diary = (Diary) event.getData();

        doctor = diary.getDoctor();

        doctorRequest = diary.getDoctorRequest() != null ? diary.getDoctorRequest() : new Doctor();
        procedure = diary.getProcedure();
        customer = diary.getCustomer();

        if (customer.getGender() != null && customer.getGender().equals(Gender.MASCULINO)) {
            gender = true;
        } else {
            gender = false;
        }

        operator = diary.getOperator() != null ? diary.getOperator() : new Operator();
        //customer.getOperator() != null ? customer.getOperator() : new Operator();


    }

    public void onEventSelectBasic(int id) {
        diary = diarysSearch.get(id);
        doctor = diary.getDoctor();
        doctorRequest = diary.getDoctorRequest();
        procedure = diary.getProcedure();
        customer = diary.getCustomer();

        if (customer.getGender() != null && customer.getGender().equals(Gender.MASCULINO)) {
            gender = true;
        } else {
            gender = false;
        }

        operator = diary.getOperator() != null ? diary.getOperator() : new Operator();
        //customer.getOperator() != null ? customer.getOperator() : new Operator();

        event = new DefaultScheduleEvent("", diary.getStartTime(), diary.getEndTime(), diary);
    }

    public void onDateSelect(SelectEvent selectEvent) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        dataNovoAtendimento = sdf.format((Date) selectEvent.getObject());
    }

    public void onDateSelectBasic() {
        diary = new Diary();
        diary.setDiarySituation(DiarySituation.SCHEDULED);
        diary.setDateConsultation(new Date());
        event = new DefaultScheduleEvent("", new Date(), new Date());

    }

    public void onEventMove(ScheduleEntryMoveEvent event) {
        ScheduleEvent e = event.getScheduleEvent();

        Diary d = diaryService.find(((Diary) (e).getData()).getId());

        d.setStartTime(e.getStartDate());
        d.setEndTime(e.getEndDate());
        d.setDateConsultation(d.getStartTime());
        d.setObservation(d.getDateConsultation() + "");
        d.setSystemUserUpdate(systemUserService.getCurrentUser());
        d.setUpdateAt(new Date());
        diaryService.update(d);

        Msg.messagemInfo(" = " + d.getStartTime());

    }

    public void onEventResize(ScheduleEntryResizeEvent event) {
//        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Event resized", "Day delta:" + event.getDayDelta() + ", Minute delta:" + event.getMinuteDelta());
//        addMessage(message);
    }

    private void addMessage(FacesMessage message) {
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

    public void diaryReport() {
        diaryService.reportsDiaryExame(diary, diarysSelected);
    }

    public Diary getDiary() {
        return diary;
    }

    public void setDiary(Diary diary) {
        this.diary = diary;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public ScheduleModel getEventModel() {
        return eventModel;
    }

    public void setEventModel(ScheduleModel eventModel) {
        this.eventModel = eventModel;
    }

    public Doctor getDoctor() {
        return doctor;
    }

    public void setDoctor(Doctor doctor) {
        this.doctor = doctor;
    }

    public List<Customer> getCustomers() {
        return customers;
    }

    public void setCustomers(List<Customer> customers) {
        this.customers = customers;
    }

    public List<Diary> getDiarys() {
        return diarys;
    }

    public void setDiarys(List<Diary> diarys) {
        this.diarys = diarys;
    }

    public Procedure getProcedureSelect() {
        return procedureSelect;
    }

    public void setProcedureSelect(Procedure procedureSelect) {
        this.procedureSelect = procedureSelect;
    }

    public List<WaitingLine> getWaitingLines() {
        return waitingLines;
    }

    public void setWaitingLines(List<WaitingLine> waitingLines) {
        this.waitingLines = waitingLines;
    }

    public WaitingLine getSelectedWaitingLine() {
        return selectedWaitingLine;
    }

    public void setSelectedWaitingLine(WaitingLine selectedWaitingLine) {
        this.selectedWaitingLine = selectedWaitingLine;
    }

    public Doctor getDoctorSelect() {
        return doctorSelect;
    }

    public void setDoctorSelect(Doctor doctorSelect) {
        this.doctorSelect = doctorSelect;
    }

    public Boolean getBlocker() {
        return blocker;
    }

    public void setBlocker(Boolean blocker) {
        this.blocker = blocker;
    }

    public Doctor getDoctorRequest() {
        return doctorRequest;
    }

    public void setDoctorRequest(Doctor doctorRequest) {
        this.doctorRequest = doctorRequest;
    }

    public Income getIncome() {
        return income;
    }

    public void setIncome(Income income) {
        this.income = income;
    }

    public List<Diary> getDiarysSelected() {
        return diarysSelected;
    }

    public void setDiarysSelected(List<Diary> diarysSelected) {
        this.diarysSelected = diarysSelected;
    }

    public List<Diary> getDiarysDisp() {
        return diarysDisp;
    }

    public void setDiarysDisp(List<Diary> diarysDisp) {
        this.diarysDisp = diarysDisp;
    }

    public void verifyOtherDiary() {
        close = false;
        addEvent(null);
        diarysDisp = diaryService.getDiaryCustomerForDate(customer, DateUtils.addHours(diary.getStartTime(), -24), DateUtils.addHours(diary.getStartTime(), 24));
        diarysSelected.add(diary);
    }

    public void selectDiaryPrint() {
    }

    public Customer getCustomerSearch() {
        return customerSearch;
    }

    public void setCustomerSearch(Customer customerSearch) {
        this.customerSearch = customerSearch;
    }

    public Procedure getProcedureSearch() {
        return procedureSearch;
    }

    public void setProcedureSearch(Procedure procedureSearch) {
        this.procedureSearch = procedureSearch;
    }

    public void searchCustomer() {
        customerSearch.setCpf(Caracter.removecaracter(customerSearch.getCpf()));
        searchCustomers = customerService.findCustomer(customerSearch);
    }

    public List<Customer> getSearchCustomers() {
        return searchCustomers;
    }

    public void setSearchCustomers(List<Customer> searchCustomers) {
        this.searchCustomers = searchCustomers;
    }

    public boolean exist() {

        aux = customerService.existCustomer(customerCreate);

        if (aux != null) {
            RequestContext context = RequestContext.getCurrentInstance();
            context.update(":customerCreate:customerDlg");
            context.execute("customerDlg.show()");
            return true;
        }
        return false;
    }

    public void loadCustomer() {
        customerCreate = aux;
    }

    public void clearCpf() {
        customerCreate.setCpf("");
        aux = null;
    }

    public void save() {
        System.err.println("SALVANDO CUSTOMER");
        try {
            customerCreate.setCpf(Caracter.removecaracter(customerCreate.getCpf()));
            if (city != null && city.getId() != null) {
                address.setCity(city);
            }
//            if (annex.getId() != null) {
//                customerCreate.setAnnex(annex);
//            }
            if (operatorCreate != null && operatorCreate.getId() != null) {
                customerCreate.setOperator(operatorCreate);
                operator = operatorCreate;
            }
            customerCreate.setAddress(address);

            customerService.save(customerCreate);
            customer = customerCreate;
            gender = customer.getGender() != null ? (customer.getGender() == Gender.MASCULINO ? true : false) : true;

            if (customerCreate.getId() != null) {
                initCustomer();
            }

            RequestContext context = RequestContext.getCurrentInstance();
            context.execute("dlgCustomerDialog.hide();");

        } catch (Exception e) {
            Msg.messagemError("Erro: Verifique os campos e tente novamente !");
        }


    }

    public void loadEditCustomer() {
        customerEdit = customerService.find(customer.getId());
        address = customerEdit.getAddress();

        if (customerEdit.getOperator() != null) {
            operatorEdit = customerEdit.getOperator();
        }

        if (address != null && address.getCity() != null) {
            city = cityService.find(address.getCity().getId());
        }
        System.err.println("LOAD" + city);

    }

    public void update() {

        System.err.println("ATUALIZANDO CUSTOMER");

        try {

            customerEdit.setCpf(Caracter.removecaracter(customerEdit.getCpf()));
            System.err.println(city);
            if (city != null && city.getId() != null) {
                address.setCity(city);
            }

            customerEdit.setAddress(address);

//            if (annex.getId() != null) {
//                customerEdit.setAnnex(annex);
//            }

            if (operatorEdit != null && operatorEdit.getId() != null) {
                customerEdit.setOperator(operatorEdit);
                operator = operatorEdit;
            }


            customer = customerEdit;
            gender = customer.getGender() != null ? (customer.getGender() == Gender.MASCULINO ? true : false) : true;
            customerService.update(customer);


            RequestContext context = RequestContext.getCurrentInstance();
            context.execute("dlgCustomerDialog.hide();");

        } catch (Exception e) {
            Msg.messagemError("Erro: Verifique os campos e tente novamente !");
        }


    }

    public void photoEdit() {
        photoedit = true;
    }

    public void photoCreate() {
        photoedit = false;
    }

    public void capture(CaptureEvent captureEvent1) {
        annex = new Annex();
        annex.setDescription("AVATAR");
        annex.setFileByte(captureEvent1.getData());
        annex.setType("image/jpeg");

        annexService.save(annex);
        if (photoedit) {
            oncaptureEdit();
        } else {
            oncapture();
        }
    }

    public void oncaptureEdit() {
        System.err.println("Salvando Edit");
        customerEdit.setAnnex(annex);

    }

    public void oncapture() {

        System.err.println("Salvando Create");
        customerCreate.setAnnex(annex);

    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public Annex getAnnex() {
        return annex;
    }

    public void setAnnex(Annex annex) {
        this.annex = annex;
    }

    public Customer getAux() {
        return aux;
    }

    public void setAux(Customer aux) {
        this.aux = aux;
    }

    public City getCity() {
        return city;
    }

    public void setCity(City city) {
        this.city = city;
    }

    public Customer getCustomerCreate() {
        return customerCreate;
    }

    public void setCustomerCreate(Customer customerCreate) {
        this.customerCreate = customerCreate;
    }

    public Operator getOperatorCreate() {
        return operatorCreate;
    }

    public void setOperatorCreate(Operator operatorCreate) {
        this.operatorCreate = operatorCreate;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public List<Procedure> getProcedures() {
        return procedures;
    }

    public void setProcedures(List<Procedure> procedures) {
        this.procedures = procedures;
    }

    public void listProcedure() {
        if (operator == null
                || (operator != null && (operator.getName().equalsIgnoreCase("sus")
                || operator.getName().equalsIgnoreCase("cortesia")))) {
            procedures = procedureService.findProcedure(procedureSearch, true);

        } else {
            procedures = procedureService.findProcedure(procedureSearch, operator);
        }
    }

    public void listDoctor() {
        doctors = doctorService.findDoctor(doctorCreate);
    }

    public Doctor getDoctorCreate() {
        return doctorCreate;
    }

    public void setDoctorCreate(Doctor doctorCreate) {
        this.doctorCreate = doctorCreate;
    }

    public List<Doctor> getDoctors() {
        return doctors;
    }

    public void setDoctors(List<Doctor> doctors) {
        this.doctors = doctors;
    }

    public void clearDoctor() {
        doctor = null;
    }

    public void clearOperator() {
        operator = null;
    }

    public void clearDoctorRequest() {
        doctorRequest = null;
    }

    public void clearProcedure() {
        procedure = null;
    }

    public void clearIncome() {
        income = null;
    }

    public List<Diary> getDiarysSearch() {
        return diarysSearch;
    }

    public void setDiarysSearch(List<Diary> diarysSearch) {
        this.diarysSearch = diarysSearch;
    }

    public Customer getCustomerSearchDiary() {
        return customerSearchDiary;
    }

    public void setCustomerSearchDiary(Customer customerSearchDiary) {
        this.customerSearchDiary = customerSearchDiary;
    }

    public void findDiaryCustomer() {
        this.diarysSearch = diaryService.findDiaryCustomer(customerSearchDiary);
    }

    public BigDecimal getDiscount() {
        return discount;
    }

    public void setDiscount(BigDecimal discount) {
        this.discount = discount;
    }

    public Boolean getRetorno() {
        return retorno;
    }

    public void setRetorno(Boolean retorno) {
        this.retorno = retorno;
    }

    public List<Diary> getDiarysRetorno() {
        return diarysRetorno;
    }

    public void setDiarysRetorno(List<Diary> diarysRetorno) {
        this.diarysRetorno = diarysRetorno;
    }

    public void loadRetorno() {
        if (diary.getRetorno()) {
            System.err.println(customer);
            if (customer == null || customer.getId() == null) {
                diary.setRetorno(false);
                strRetorno = "Selecione o Paciente";
                return;
            }

            diarysRetorno = diaryService.loadReturnDiaryCustomer(customer);
            if (!diarysRetorno.isEmpty()) {
                strRetorno = "";
                RequestContext.getCurrentInstance().execute("retornoDialog.show()");
            } else {
                diary.setRetorno(false);
                strRetorno = "Não há registros de atendimentos";
            }
        } else {
            strRetorno = "";
        }
    }

    public void selectRetorno() {
        if (diary.getRetorno()) {
            procedure = diary.getRetornoDiary().getProcedure();
            System.err.println(procedure);
        }
    }

    public void calcDiscount() {
        income.setTotalAmount(income.getAmount());
        income.setAmountPaid(income.getAmount());

        if ((income.getDiscount() != null)
                && (!income.getDiscount().equals(BigDecimal.ZERO))) {
            income.setTotalAmount(income.getAmount().subtract(income.getDiscount()));
            income.setAmountPaid(income.getTotalAmount());
            discount = BigDecimal.ZERO;
        }

    }

    public void calcDiscountPorce() {
        if (discount == null) {
            discount = BigDecimal.ZERO;
            return;
        }
        if (discount != null && discount.compareTo(BigDecimal.ZERO) == 0) {
            if ((income.getDiscount() == null)
                    || (income.getDiscount().compareTo(BigDecimal.ZERO) == 0)) {

                income.setTotalAmount(income.getAmount());
                income.setAmountPaid(income.getAmount());
            }
            return;
        }
        if (income.getAmount() != null) {
            income.setTotalAmount(income.getAmount());
            income.setAmountPaid(income.getAmount());
            if (discount != null) {
                income.setTotalAmount(income.getAmount().subtract(income.getAmount().
                        multiply(discount)));
            }
            income.setAmountPaid(income.getTotalAmount());

            income.setDiscount(BigDecimal.ZERO);
        }
    }

    public String getStrRetorno() {
        return strRetorno;
    }

    public void setStrRetorno(String strRetorno) {
        this.strRetorno = strRetorno;
    }

    public boolean isGender() {
        return gender;
    }

    public void setGender(boolean gender) {
        this.gender = gender;
    }

    public void loadGender() {

        if (customer.getGender() != null && customer.getGender().equals(Gender.MASCULINO)) {
            gender = true;
        } else {
            gender = false;
        }
    }

    public void saveGender() {
        if (gender) {
            customer.setGender(Gender.MASCULINO);
        } else {
            customer.setGender(Gender.FEMININO);
        }
    }

    public Customer getCustomerEdit() {
        return customerEdit;
    }

    public void setCustomerEdit(Customer customerEdit) {
        this.customerEdit = customerEdit;
    }

    public List<Operator> getOperators() {
        return operators;
    }

    public void setOperators(List<Operator> operators) {
        this.operators = operators;
    }

    public void handleSelect(SelectEvent event) {
    }

    public void cleanPrint() {
        diarysSelected = new ArrayList<Diary>();
    }

    public Customer getCustomerSelect() {
        return customerSelect;
    }

    public void setCustomerSelect(Customer customerSelect) {
        this.customerSelect = customerSelect;
    }

    public void selectCustomer() {
        if (customerSelect != null && customerSelect.getId() != null) {
            customer = customerService.find(customerSelect.getId());
            if (customer != null && customer.getOperator() != null) {
                operator = customer.getOperator();
            }
        }

        loadGender();
    }

    public void selectOperator() {
        operator = operatorSelect;
    }

    public void selectProcedureDialog() {
        procedure = procedureSelectDialog;
    }

    public void selectDoctorDialog() {
        doctor = doctorSelectDialog;
    }

    public void selectDoctorRequestDialog() {
        doctorRequest = doctorRequestSelect;
    }

    public Operator getOperatorSelect() {
        return operatorSelect;
    }

    public void setOperatorSelect(Operator operatorSelect) {
        this.operatorSelect = operatorSelect;
    }

    public Procedure getProcedureSelectDialog() {
        return procedureSelectDialog;
    }

    public void setProcedureSelectDialog(Procedure procedureSelectDialog) {
        this.procedureSelectDialog = procedureSelectDialog;
    }

    public Doctor getDoctorSelectDialog() {
        return doctorSelectDialog;
    }

    public void setDoctorSelectDialog(Doctor doctorSelectDialog) {
        this.doctorSelectDialog = doctorSelectDialog;
    }

    public Doctor getDoctorRequestSelect() {
        return doctorRequestSelect;
    }

    public void setDoctorRequestSelect(Doctor doctorRequestSelect) {
        this.doctorRequestSelect = doctorRequestSelect;
    }

    public boolean isPhotoedit() {
        return photoedit;
    }

    public void setPhotoedit(boolean photoedit) {
        this.photoedit = photoedit;
    }

    public void cleanIncome() {
        income = new Income();
    }

    public boolean verifyAdmin() {
        return systemUserService.verifyAdmin();
    }

    public boolean after(Date d) {
        if (d == null) {
            System.err.println(d);
            return false;
        }
        Calendar gc = GregorianCalendar.getInstance();
        gc.add(GregorianCalendar.DAY_OF_MONTH, 1);
        gc.set(GregorianCalendar.MINUTE, 0);
        gc.set(GregorianCalendar.SECOND, 0);
        gc.set(GregorianCalendar.MILLISECOND, 0);

        if (d.after(gc.getTime())) {
            return true;
        }
        return false;
    }

    public Operator getOperatorEdit() {
        return operatorEdit;
    }

    public void setOperatorEdit(Operator operatorEdit) {
        this.operatorEdit = operatorEdit;
    }

    /**
     * Retorna a idade do paciente
     *
     * @return
     */
    public int getAge() {
        int idade = 0;
        if (customer.getDateBirth() != null) {
            Calendar c = new GregorianCalendar();
            Calendar dateBirth = new GregorianCalendar();
            dateBirth.setTime(customer.getDateBirth());

            idade = c.get(Calendar.YEAR) - dateBirth.get(Calendar.YEAR);

            dateBirth.add(Calendar.YEAR, idade);

            if (c.before(dateBirth)) {
                idade--;
            }
        }
        return idade;

    }

    public ScheduleModel getEventModelHoje() {
        return eventModelHoje;
    }

    public void setEventModelHoje(ScheduleModel eventModelHoje) {
        this.eventModelHoje = eventModelHoje;
    }
    
    
}
